﻿
using Leadyo.Common;
using Leadyo.WebService.ServiceWCF;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Leadyo.WebService
{
   public class WebAbsDAL<T> where T : class,new()
   {
       public string tableName = "";
       public string keyName = "";
       public string outoKeyValue = "";
       public string sortIndex = "";
       public Type o= null;
        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <summary>
        /// 默认构造函数
        /// </summary>
       public WebAbsDAL()
        {
            
        }   
        public void Init()
        {
            o = typeof(T);
            var t = typeof(T);
            var attribute = t.GetCustomAttributes(typeof(TableAttribute),true).FirstOrDefault();
            tableName = ((TableAttribute)attribute).TableName;//表名
            keyName = ((TableAttribute)attribute).KeyName;//表主键
            outoKeyValue=((TableAttribute)attribute).OutoKeyValue;//自动递增键
            sortIndex = ((TableAttribute)attribute).sortIndex;//排序字段
        }

        /// <summary>
        /// 新增数据
        /// </summary>
        /// <param name="obj">实体类</param>
        /// <returns></returns>
        public virtual int Insert(object obj)
        {
            ServiceWCFClient webClient = new ServiceWCFClient();
            byte[] bytes = Tools.CompressionObject(obj);
            if (webClient.Insert(bytes))
                return 1;
            else
                return 0;


        }
        /// <summary>
        /// 删除操作
        /// </summary>
        /// <param name="key">主键</param>
        /// <returns></returns>
        public virtual bool Delete(string key)
        {
            //string sql = "";
            //sql = string.Format(" delete from {0} where {1}={2} ", tableName, keyName, key);
            //if (BaseBuildSql.ExecuteNonQuery(sql) > 0)
            //{
            //    return true;
            //}
            //else
            //{
            //    return false;
            //}
            
            ServiceWCFClient webClient = new ServiceWCFClient();
            byte[] bytes = Tools.CompressionObject(o);

            if (webClient.Delete(key, bytes))
                return true;
            else
                return false;


        }
        /// <summary>
        /// 数据更新
        /// </summary>
        /// <param name="obj">实体类</param>
        /// <returns></returns>
        public virtual bool Update(T obj)
        {
            //string strFiled = "";
            //string filedValue = "";
            //string KeyValue = "";
            //string sql = "";
            //System.Reflection.PropertyInfo[] properties = obj.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

            //foreach (System.Reflection.PropertyInfo item in properties)
            //{
            //    if (item.Name == keyName)
            //    {
            //        KeyValue = item.GetValue(obj, null).ToString();
            //    }
            //    else
            //    {
            //        strFiled += string.Format("{0}='{1}',", item.Name, item.GetValue(obj, null));
            //    }
            //}
            //strFiled = strFiled.Trim(',');
            //sql = string.Format("UPDATE {0} set {1} WHERE {2} ='{3}'", tableName, strFiled, keyName, KeyValue);
            //if (BaseBuildSql.ExecuteNonQuery(sql) > 0)
            //{
            //    return true;
            //}
            //else
            //{
            //    return false;
            //}

            ServiceWCFClient webClient = new ServiceWCFClient();
            byte[] bytes = Tools.CompressionObject(obj);
            if (webClient.Update(bytes))
                return true;
            else
                return false;

        }
        /// <summary>
        /// 获取数据最后一条
        /// </summary>
        /// <returns></returns>
        public virtual List<T> GetLastEntriyList()
        {
            //string sql = "";
            //if (string.IsNullOrEmpty(sortIndex))
            //    sql = string.Format(" SELECT top 1 * FROM {0} ORDER BY {1} DESC", tableName, sortIndex);//获取最前一条数据
            //else
            //    sql = string.Format(" SELECT top 1 * FROM {0} ORDER BY {1} DESC", tableName, sortIndex);//获取最前一条数据
            ServiceWCFClient webClient = new ServiceWCFClient();
            byte[] obj = Tools.CompressionObject(o);
            DataSet ds = Tools.DecompressionDataSet(webClient.GetLastEntriyList(obj));
            var lst = ConvertHelper<T>.DataTableToList(ds.Tables[0]);
            return lst;
        }
        public virtual T GetModel(string sql)
        {
            //return DataReaderToEntity(BaseBuildSql.GetModel(sql));
            return null;
        }
        /// <summary>
        /// 判断是否存在数据
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="FieldName">字段</param>
        /// <param name="FieldValue">字段值</param>
        /// <returns></returns>
        public virtual bool CheckNoExists(string TableName, string FieldName, string FieldValue)
        {
            string sql = "SELECT Count(*) C FROM {0} WHERE {1}='{2}' ;";
            sql = string.Format(sql, TableName, FieldName, FieldValue);
            return 1 > 0;
        }
        /// <summary>
        /// 获取数据最前一条
        /// </summary>
        /// <returns></returns>
        public virtual List<T> GetFirsttEntriyList()
        {
            ServiceWCFClient webClient = new ServiceWCFClient();
            byte[] obj = Tools.CompressionObject(o);
            DataSet ds = Tools.DecompressionDataSet(webClient.GetFirsttEntriyList(obj));
            var lst = ConvertHelper<T>.DataTableToList(ds.Tables[0]);
            return lst;
            return null;

        }
        /// <summary>
        /// 获取表结构数据
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <returns></returns>
        public virtual DataTable GetDataTableBySql(string sql)
        {
            return null;
        }
        /// <summary>
        /// 获取数据集
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <returns></returns>
        public virtual DataSet GetDataSetBySql(string sql)
        {
            return null;
        }
        /// <summary>
        ///对表格进行转换
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        protected virtual T DataReaderToEntity(DataRow dr)
        {
            T obj = new T();
            PropertyInfo[] pis = obj.GetType().GetProperties();

            foreach (PropertyInfo pi in pis)
            {
                try
                {
                    if (dr[pi.Name].ToString() != "")
                    {
                        pi.SetValue(obj, dr[pi.Name] ?? "", null);
                    }
                }
                catch { }
            }
            return obj;
        }
        /// <summary>
        /// 返回执行数据条数，如果失败就为0
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <returns></returns>
        public virtual int ExecuteNonQuery(string sql)
        {
            return 1;
        }
        private bool readerExists(SqlDataReader dr, string columnName)
        {

            dr.GetSchemaTable().DefaultView.RowFilter = "ColumnName= '" + columnName + "'";

            return (dr.GetSchemaTable().DefaultView.Count > 0);

        }
   }
}
